package io.binghe.im.openai.infrastructure.service.impl;

import com.alibaba.fastjson.JSON;
import io.binghe.im.openai.common.constants.OpenAIConstants;
import io.binghe.im.openai.common.enums.HttpCode;
import io.binghe.im.openai.common.exception.OpenAIException;
import io.binghe.im.openai.common.httpclient.HttpClient;
import io.binghe.im.openai.domain.chapgpt.model.message.AIMessage;
import io.binghe.im.openai.domain.chapgpt.model.request.AIRequest;
import io.binghe.im.openai.domain.chapgpt.model.vo.ChoiceInfo;
import io.binghe.im.openai.domain.service.OpenAIInteractiveService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description 对接OpenAI
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
@Service
@ConditionalOnProperty(name = "bh-im-openai.type", havingValue = "chatgpt")
public class ChatGPTOpenAIInteractiveService implements OpenAIInteractiveService {
    private final Logger logger = LoggerFactory.getLogger(ChatGPTOpenAIInteractiveService.class);

    @Value("${bh-im-openai.chatgpt.key}")
    private String aiKey;

    @Value("${bh-im-openai.chatgpt.api}")
    private String api;

    @Override
    public String sendMessage(String requestData) throws IOException {
        if (StringUtils.isEmpty(requestData)){
            throw new OpenAIException(HttpCode.PARAMS_ERROR);
        }
        try(CloseableHttpClient httpClient = HttpClient.createSSLClientDefault()){
            HttpPost httpPost = new HttpPost(api);
            httpPost.addHeader(OpenAIConstants.CONTENT_TYPE, OpenAIConstants.APPLICATION_JSON);
            httpPost.addHeader(OpenAIConstants.AUTHORIZATION, OpenAIConstants.BEARER.concat(aiKey));
            AIRequest request = new AIRequest(requestData);
            StringEntity entity = new StringEntity(JSON.toJSONString(request), ContentType.create(OpenAIConstants.TEXT_JSON, OpenAIConstants.CHARSET_UTF_8));
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 响应成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String responseStr = EntityUtils.toString(response.getEntity());
                AIMessage aiMessage = JSON.parseObject(responseStr, AIMessage.class);
                List<ChoiceInfo> choices = aiMessage.getChoices();
                // 拼接返回结果
                StringBuilder resultBuilder = new StringBuilder();
                for (ChoiceInfo choice : choices){
                    resultBuilder.append(choice.getText());
                }
                return resultBuilder.toString();
            }else{
                logger.error("调用ChatGPT接口异常, 返回的状态码为: {}" , response.getStatusLine().getStatusCode());
            }
        }
        return OpenAIConstants.DEFAULT_MESSAGE;
    }
}
